package com.itheima.controller.interceptor;


import com.alibaba.fastjson.JSON;
import com.itheima.common.GetSessionId;
import com.itheima.common.Result;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class IsLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        HttpSession session = req.getSession();
        Object employee = session.getAttribute("Employee");
        if (employee != null) {
            long id = (long) employee;
            GetSessionId.SetId(id);
            return true;
        }

        Object code = session.getAttribute("user");
        if (code !=null){
            long id = (long) code;
            GetSessionId.SetId(id);
            return true;
        }

        //如果未登录, 则返回未登录结果
        //通过json字符串响应数据
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return false;


    }
}
